package fun.wxy.camera.fragment;

import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.fragment.app.Fragment;

import com.jiangdg.usb.USBMonitor;
import com.jiangdg.uvc.UVCCamera;

import fun.wxy.camera.R;

/**
 * IR相机
 */
public class IrCameraFragment extends Fragment {

    private Surface surface;

    private USBMonitor mUSBMonitor;
    private UVCCamera irCamera;

    private final String TAG = "IrCameraFragment";

    private final int IR_CAMERA_VID = 11134;
    private final int IR_CAMERA_PID = 22651;

    private final int CAMERA_WIDTH = 640;
    private final int CAMERA_HEIGHT = 480;

    public IrCameraFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mUSBMonitor = new USBMonitor(requireContext(), new USBMonitor.OnDeviceConnectListener() {
            /**
             * 检测到USB设备接入
             */
            @Override
            public void onAttach(UsbDevice device) {
                Log.d(TAG, "USB设备接入：" + device.getDeviceName());

                // 判断是否有权限
                if (mUSBMonitor.hasPermission(device)) {
                    Log.d(TAG, "已获取设备权限，设备：" + device.getDeviceName());

                    final int vendorId = device.getVendorId();
                    final int productId = device.getProductId();

                    if (vendorId == IR_CAMERA_VID && productId == IR_CAMERA_PID) {
                        USBMonitor.UsbControlBlock ctrlBlock = mUSBMonitor.openDevice(device);

                        // 打开IR相机
                        openIRCamera(ctrlBlock);
                    }
                } else {
                    // 自动请求权限
                    mUSBMonitor.requestPermission(device);
                }
            }


            /**
             * 检测到USB设备拔出
             */
            @Override
            public void onDetach(UsbDevice device) {
                Log.d(TAG, "USB设备拔出：" + device.getDeviceName());
            }

            /**
             * 成功连接USB设备，获取到控制块
             * 用户授权成功时，进入这个回调
             */
            @Override
            public void onConnect(UsbDevice device, USBMonitor.UsbControlBlock ctrlBlock, boolean createNew) {
                Log.d(TAG, "成功连接USB设备：" + device.getDeviceName());

                final int deviceId = device.getDeviceId();
                final int productId = device.getProductId();

                // 获取设备的控制权
                if (deviceId == IR_CAMERA_PID && productId == IR_CAMERA_PID) {
                    // 打开IR相机
                    openIRCamera(ctrlBlock);
                }
            }

            /**
             * USB设备断开
             */
            @Override
            public void onDisconnect(UsbDevice device, USBMonitor.UsbControlBlock ctrlBlock) {
                releaseCamera();
            }

            /**
             * USB权限被用户拒绝
             */
            @Override
            public void onCancel(UsbDevice device) {
                Log.d(TAG, "USB权限被用户拒绝：" + device.getDeviceName());
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_ir_camera, container, false);

        ImageView backImage = rootView.findViewById(R.id.btn_back);
        backImage.setOnClickListener(v -> requireActivity().getSupportFragmentManager().popBackStack());

        SurfaceView surfaceView = rootView.findViewById(R.id.ir_camera);
        SurfaceHolder holder = surfaceView.getHolder();
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                surface = holder.getSurface(); // 直接获取 Surface
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                // Surface 尺寸改变时的处理（如需调整相机参数）
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (irCamera != null) {
                    irCamera.stopPreview(); // 立即停止预览
                }

                surface = null; // 释放 Surface 引用
            }
        });

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();

        if (mUSBMonitor != null && !mUSBMonitor.isRegistered()) {
            mUSBMonitor.register();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        releaseCamera(); // 停止预览并销毁相机
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mUSBMonitor != null) {
            mUSBMonitor.unregister(); // 注销监听
            mUSBMonitor.destroy();    // 释放资源
            mUSBMonitor = null;
        }
    }

    private void openIRCamera(USBMonitor.UsbControlBlock ctrlBlock) {
        try {
            // 释放旧实例
            if (irCamera != null) {
                irCamera.destroy();
                irCamera = null;
            }

            irCamera = new UVCCamera();
            irCamera.open(ctrlBlock);
            irCamera.setPreviewSize(CAMERA_WIDTH, CAMERA_HEIGHT, UVCCamera.FRAME_FORMAT_MJPEG);
            irCamera.setPreviewDisplay(surface);
            irCamera.startPreview();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void releaseCamera() {
        if (irCamera != null) {
            irCamera.stopPreview();
            irCamera.destroy();
            irCamera = null;
        }
    }
}